<template>
    <div>
        <div class="content white-block">
            <div class="toolbar">
                <div class="provider">
                    <el-select v-model="nameValue" placeholder="请选择">
                        <el-option
                            v-for="item in nameOptions"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                        </el-option>
                    </el-select>
                    <el-input v-model="APIEditorInput" placeholder="请输入" class="input ml10"
                              @keyup.enter.native="APIEditorSystem(1)"></el-input>
                    <el-button type="primary" class="ml10" @click="APIEditorSystem(1)">查询</el-button>
                </div>
                <div class="text-right">
                    <el-button type="primary" @click="newAPIInformation=true">新建</el-button>
                </div>
            </div>
            <div class="table atomicTable mt20">
                <table-example :data="tableData" :tableColumn="header" :slotColumns="slotColumns"
                               v-loading="loading"
                               @cell-mouse-enter="handClick"
                               @row-click="handleClick"
                               class="mt20">
                    <template slot="status" slot-scope="scope">
                        <span v-if="scope.row.status == 0">编辑中</span>
                        <span v-if="scope.row.status == 1">待审核</span>
                        <span v-if="scope.row.status == 2">待发布</span>
                        <span v-if="scope.row.status == 3">已发布</span>
                        <span v-if="scope.row.status == 4">已作废</span>
                    </template>
                    <template slot="operation" slot-scope="scope">
                        <!--                        <el-link type="primary" :underline="false" class="mr10" @click="APIDetails(scope.row, true)"-->
                        <!--                                 v-if="scope.row.status != 4 || scope.row.status == 1">详情-->
                        <!--                        </el-link>-->
                        <!--                        <el-link type="primary" :underline="false" class="mr10" @click="APIDetails(scope.row)"-->
                        <!--                                 v-if="scope.row.status !== 4">编辑-->
                        <!--                        </el-link>-->
                        <el-link type="primary" :underline="false" class="mr10" @click.stop
                                 @click="submitButton(scope.row)"
                                 v-if="scope.row.status == 0">提交审核
                        </el-link>
                        <el-link type="primary" :underline="false" class="mr10" @click.stop
                                 @click="enableButton(scope.row)"
                                 v-if="scope.row.status == 4">启用
                        </el-link>
                        <el-link type="primary" :underline="false" class="mr10" v-if="scope.row.status != 4" @click.stop
                                 @click="download(scope.row)">下载
                        </el-link>
                    </template>
                </table-example>
                <page :data="APIEditorPage" v-if="APIEditorPage" class="mt30 page" @jumpPage="APIEditorSystem"></page>
            </div>
        </div>

        <!--  新建API信息弹框-->
        <dialog-msk :show.sync="newAPIInformation" ref="newSystemRef" :toBody="false" :center="true" width="12rem"
                    :noEsc="false"
                    :noModal="false"
                    @cancel="newAPICancel" :marginTop="'10vh'"
                    title="新建API信息">
            <span slot="footer" class="dialog-footer">
                <span slot="footer">
                    <el-button @click="newAPIInformation=false">取 消</el-button>
                    <!-- <el-button type="primary" v-if="detailsId" @click="modify">保 存</el-button> -->
                    <el-button type="primary" @click="saveNewAPIInformation">保 存</el-button>
                </span>
            </span>
            <el-form ref="infoFormRef" :model="infoForm" :rules="infoRules" label-width="2rem" class="scrollHeight">
                <div class="current provider mapOutMsg">
                    <breadcrumb :title="'基本信息'" class="breadcrumb"></breadcrumb>
                </div>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="选择服务：" prop="servcode" class="fontItem">
                            <el-select v-model="infoForm.servcode" placeholder="请选择" class="inputWidthD"
                                       @change="getServname" filterable>
                                <el-option v-for="item in infoForm.serviceOptions"
                                           :key="item.serviceid"
                                           :label="item.servname + ' (' + item.servcode + ') '"
                                           :value="item.servcode">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="联系人：" prop="name">
                            <el-input v-model="infoForm.name" placeholder="请输入内容" class="inputWidthD"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="联系方式：" prop="phone">
                            <el-input v-model="infoForm.phone" placeholder="请输入内容" class="inputWidthD"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="数据源部门：" prop="providedept">
                            <select-tree class="inputWidthD"
                                         :showSearch="true"
                                         :loading.sync="provideDeptTree.loading"
                                         :renderTree.sync="provideDeptTree.renderTree"
                                         :lazy.sync="provideDeptTree.lazy"
                                         :clearable.sync="provideDeptTree.clearable"
                                         :filterable.sync="provideDeptTree.filterable"
                                         :model.sync="infoForm.providedept"
                                         :accordion.sync="provideDeptTree.accordion"
                                         :expandAll.sync="provideDeptTree.expandAll"
                                         :provideDeptTree="provideDeptTree"
                                         @loadNode="dataLoadNode"
                                         @nodeClick="dataConsumersNodeClick"
                                         @filterMethod="dataFilter"
                                         :props="dataConsumersprops"
                                         :options="provideDeptTree.options">
                            </select-tree>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="服务访问地址：" prop="apiaddress">
                            <el-input v-model="infoForm.apiaddress" placeholder="请输入内容" class="inputWidthD"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="共享类型：" prop="shareType">
                            <el-select v-model="infoForm.shareType" placeholder="请选择" class="inputWidthD">
                                <el-option
                                    v-for="item in typeOptions"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="共享平台资源id：" prop="dataPlatformId">
                            <el-input v-model="infoForm.dataPlatformId" placeholder="请输入内容"
                                      class="inputWidthD"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="数据更新周期：" prop="dataUpdateCycle">
                            <el-select v-model="infoForm.dataUpdateCycle" placeholder="请选择" class="inputWidthD">
                                <el-option
                                    v-for="item in infoForm.cycleOptions"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <div class="current provider mapOutMsg">
                            <breadcrumb :title="'请求示例'" class="breadcrumb"></breadcrumb>
                        </div>
                        <el-form-item>
                            <el-input v-model="infoForm.reqExample"
                                      type="textarea"
                                      class="textareaWidthD" :rows="5"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <div class="current provider mapOutMsg">
                            <breadcrumb :title="'返回示例'" class="breadcrumb"></breadcrumb>
                        </div>
                        <el-form-item>
                            <el-input v-model="infoForm.respExample"
                                      type="textarea"
                                      class="textareaWidthD" :rows="5"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <div class="current provider mapOutMsg">
                            <breadcrumb :title="'服务说明'" class="breadcrumb"></breadcrumb>
                        </div>
                        <el-form-item prop="description">
                            <el-input v-model="infoForm.description"
                                      type="textarea"
                                      class="textareaWidthD" :rows="5"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </dialog-msk>

        <!-- 详情/修改抽屉 -->
        <el-drawer
            v-if=serListDetailsFlag
            :visible.sync="serListDetailsFlag"
            direction="rtl"
            size="70%">
            <new-drawer :id.sync="id" :detailsId.sync="detailsId" @closeDrawer="closeDrawer"></new-drawer>
        </el-drawer>
    </div>
</template>

<script>
    import dialogMsk from '../../components/dialog'
    import tableExample from '../../components/table'
    import page from '../../components/pagination'
    import breadcrumb from '../../components/breadcrumb'
    import newDrawer from '../../page/monitoring/new-api-editor'
    import selectTree from '../../components/select-tree'

    export default {
        data() {
            let _this = this
            return {
                tableData: [],
                header: [
                    {
                        prop: 'servname',
                        label: '服务名称',
                        minWidth: '15%',
                        align: 'left',
                        tooltip: true
                    },
                    {
                        prop: 'servcode',
                        label: '服务编码',
                        minWidth: '15%',
                        align: 'left',
                        tooltip: true
                    },
                    {
                        prop: 'servversion',
                        label: '服务版本',
                        minWidth: '10%',
                        align: 'left'
                    },
                    {
                        prop: 'status',
                        label: '状态',
                        minWidth: '10%',
                        align: 'center'
                    },
                    {
                        prop: 'operation',
                        label: '操作',
                        minWidth: '15%',
                        align: 'center'
                    }
                ],
                slotColumns: ['operation', 'status'],
                currentPage: 1,
                pageSize: 10,
                nameOptions: [
                    {
                        value: '1',
                        label: '服务名称'
                    }, {
                        value: '2',
                        label: '服务编码'
                    }
                ],
                nameValue: '1',
                typeOptions: [
                    {
                        value: '1',
                        label: '内部共享'
                    },
                    {
                        value: '2',
                        label: '外部共享'
                    },
                    {
                        value: '3',
                        label: '内外部共享'
                    }
                ], // 共享类型选项
                APIEditorInput: '', // 列表输入框
                APIEditorPage: null,
                serListDetailsFlag: false,
                id: null,
                detailsId: null,
                loading: false,
                newAPIInformation: false,
                infoForm: {
                    serviceOptions: [], // 选择服务选项
                    servcode: '', // 选择服务
                    servname: '', // 服务名称
                    servversion: '', // 服务版本
                    name: '', // 联系人姓名
                    phone: '', // 联系方式
                    providedept: {
                        value: '',
                        label: ''
                    },
                    apiaddress: '', // 服务访问地址
                    shareType: '', // 共享类型
                    dataUpdateCycle: '', // 数据更新周期
                    cycleOptions: [
                        {
                            value: '1',
                            label: '实时'
                        },
                        {
                            value: '2',
                            label: '每小时'
                        },
                        {
                            value: '3',
                            label: '每天'
                        },
                        {
                            value: '4',
                            label: '每月'
                        },
                        {
                            value: '5',
                            label: '每季度'
                        },
                        {
                            value: '6',
                            label: '每半年'
                        },
                        {
                            value: '7',
                            label: '每年'
                        },
                        {
                            value: '8',
                            label: '不更新'
                        },
                        {
                            value: '9',
                            label: '不定时'
                        }
                    ], // 数据更新周期选项
                    dataPlatformId: null, // 共享平台资源id
                    reqExample: '', // 请求示例
                    respExample: '', // 返回示例
                    description: '' // 服务说明
                },
                infoRules: {
                    servcode: [
                        {required: true, message: '请选择服务', trigger: 'change'}
                    ],
                    name: [
                        {min: 0, max: 10, message: '长度不超过10', trigger: 'blur'}
                    ],
                    phone: [
                        {pattern: /^[0-9-]{0,15}$/, message: '联系方式为数字类型或"-"且长度不超过15', trigger: 'blur'}
                    ],
                    providedept: [
                        {required: true, message: '请选择数据源部门', trigger: 'change'}
                    ],
                    apiaddress: [
                        {required: false, message: '请输入访问地址', trigger: 'blur'},
                        {pattern: /^(http:\/\/|https:\/\/).+$/, message: '请输入有效地址', trigger: 'blur'}
                    ],
                    shareType: [
                        {required: true, message: '请选择共享类型', trigger: 'change'}
                    ],
                    dataPlatformId: [
                        {pattern: /^\d{0,50}$/, message: 'ID为数字类型且长度不超过50', trigger: 'blur'}
                    ],
                    dataUpdateCycle: [
                        {required: true, message: '请选择更新周期', trigger: 'change'}
                    ],
                    // reqExample: [
                    //     {min: 0, max: 200, message: '长度不超过200', trigger: 'blur'}
                    // ],
                    // respExample: [
                    //     {min: 0, max: 200, message: '长度不超过200', trigger: 'blur'}
                    // ],
                    description: [
                        {min: 0, max: 500, message: '长度不超过200', trigger: 'blur'}
                    ]
                },
                sidebarStyle: null,
                selectTreeFilter: null,
                provideDeptTree: { // 数据源部门树形下拉框参数
                    lazy: true,
                    clearable: false,
                    filterable: false,
                    accordion: false, // 一次只展开一个同级节点
                    expandAll: false, // 默认展开所有节点
                    loading: false, // 是否显示loading
                    renderTree: true, // 是否显示tree，隐藏后再次显示以此来重新渲染
                    options: []
                },
                // 数据源部门
                dataConsumersprops: {
                    value: 'code', // ID字段名
                    label: 'label', // 显示名称
                    children: 'children', // 子级字段名
                    isLeaf: function (data, node) { // 是否为子节点
                        if ((_this.provideDeptTree.lazy && !data.expand) || (!_this.provideDeptTree.lazy && !data.children)) return true
                    }
                }
            }
        },
        created() {
            // let lett = this
            // document.onkeydown = function (e) {
            //     let key = window.event.keyCode
            //     if (key === 13) {
            //         lett.APIEditorSystem(1)
            //     }
            // }
        },
        mounted() {
            this.getAPIEditorData()
            this.getSelect()
        },
        methods: {
            // 获取API编辑页面列表数据
            getAPIEditorData() {
                this.loading = true
                this.$http.get('/APIEdit/selectAtomService', {
                    current: this.currentPage || 1,
                    message: this.APIEditorInput,
                    size: this.pageSize,
                    type: this.nameValue
                }).then(result => {
                    this.loading = false
                    if (result.success) {
                        this.APIEditorPage = result.data
                        this.tableData = result.data.records
                    }
                }).catch(() => {
                    this.loading = false
                })
            },
            // 分页
            APIEditorSystem(val) {
                this.currentPage = val
                this.getAPIEditorData()
            },
            // 获取选择服务数据
            getSelect() {
                this.$http.get('/EsbInboundMain/selectAllService').then(result => {
                    if (result.success) {
                        for (let i = 0; i < result.data.length; i++) {
                            this.infoForm.serviceOptions.push(result.data[i])
                        }
                    }
                })
            },
            // 获取服务名称
            getServname(servcode) {
                this.$http.get('/EsbInboundMain/selectServiceByServcode', {
                    servcode: servcode
                }).then(result => {
                    if (result.success) {
                        this.infoForm.servname = result.data[0].servname
                        this.infoForm.servversion = result.data[0].servversion
                    }
                })
            },
            // 获取树形结构数据-搜索
            dataFilter(event, callback) {
                if (this.selectTreeFilter) clearTimeout(this.selectTreeFilter)
                if (event || event !== '') {
                    console.log(342)
                    this.selectTreeFilter = setTimeout(() => {
                        this.provideDeptTree.loading = true
                        this.provideDeptTree.lazy = false
                        this.$http.get('/APIEdit/getDept', {
                            message: event
                        }).then(result => {
                            if (result.success) {
                                this.provideDeptTree.loading = false
                                this.provideDeptTree.options = this.$method.treeProcess(result.data)
                            }
                            this.selectTreeFilter = null
                            if (callback) callback()
                        }).catch(() => {
                            this.provideDeptTree.loading = false
                            this.selectTreeFilter = null
                            if (callback) callback()
                        })
                    }, 300)
                } else {
                    this.selectTreeFilter = setTimeout(() => {
                        this.provideDeptTree.loading = true
                        this.provideDeptTree.lazy = true
                        if (callback) callback()
                    }, 300)
                }

            },
            // 获取树形结构数据-懒加载
            dataLoadNode(parentId, callback) {
                if (!parentId && this.firstDeptList) {
                    this.provideDeptTree.loading = false
                    if (callback) callback(this.firstDeptList)
                } else {
                    this.$http.get('/APIEdit/getDeptName', {
                        id: parentId || 0
                    }).then(result => {
                        if (result.success) {
                            if (result.data[0]) {
                                result.data.forEach(item => {
                                    if (!item.label) {
                                        item.label = item.abbreviation || item.name
                                    }
                                })
                            }
                            this.provideDeptTree.loading = false
                            if (callback) callback(result.data)
                        }
                    }).catch(() => {
                        this.provideDeptTree.loading = false
                        this.$message({
                            type: 'info',
                            message: '获取部门失败!'
                        })
                    })
                }
            },
            // 切换触发的事件
            dataConsumersNodeClick(node, callback) {
                if (node.haschildren) return
                if (callback) callback()
            },
            // 详情/修改按钮
            APIDetails(row, id) {
                this.id = id
                this.detailsId = row.id
                this.serListDetailsFlag = true
            },
            // 提交审核
            submitButton(row) {
                this.loading = true
                this.$http.get('/APIEdit/operateApi', {
                    id: row.id
                }).then(result => {
                    this.loading = false
                    if (result.success) {
                        this.$message({
                            type: 'success',
                            message: result.data
                        })
                        this.getAPIEditorData()
                    }
                }).catch(() => {
                    this.loading = false
                })
            },
            // 启用
            enableButton(row, type) {
                this.$http.get('/APIEdit/operateApiStartUsing', {
                    id: row.id
                }).then(result => {
                    if (result.success) {
                        this.$message({
                            type: 'success',
                            message: result.data
                        })
                        this.getAPIEditorData()
                    }
                })
            },

            // 下载
            download(row) {
                window.open(window.localStorage.getItem('ajaxApi') + '/APIEdit/download?id=' + row.id)
                this.$message({
                    type: 'success',
                    message: '下载成功！'
                })
                this.closeDrawer()
            },
            // 关闭新建API信息弹框
            newAPICancel() {
                this.$refs.infoFormRef.resetFields()
            },
            // 保存新建API信息
            saveNewAPIInformation() {
                if (this.infoForm.dataPlatformId === null) {
                    this.infoForm.dataPlatformId = ''
                } else {
                    this.infoForm.dataPlatformId = Number(this.infoForm.dataPlatformId)
                }
                this.$refs.infoFormRef.validate(valid => {
                    if (valid) {
                        this.$http.post('/APIEdit/saveApi', {
                            servcode: this.infoForm.servcode,
                            servname: this.infoForm.servname,
                            servversion: this.infoForm.servversion,
                            name: this.infoForm.name,
                            phone: this.infoForm.phone,
                            providedept: this.infoForm.providedept.label,
                            providedeptCode: this.infoForm.providedept.value,
                            apiaddress: this.infoForm.apiaddress,
                            shareType: this.infoForm.shareType,
                            reqExample: this.infoForm.reqExample,
                            respExample: this.infoForm.respExample,
                            description: this.infoForm.description,
                            dataUpdateCycle: Number(this.infoForm.dataUpdateCycle),
                            dataPlatformId: this.infoForm.dataPlatformId
                        }).then(result => {
                            if (result.success) {
                                this.$message({
                                    type: 'success',
                                    message: '新建成功!'
                                })
                                this.newAPIInformation = false
                                this.getAPIEditorData()
                            }
                        })
                    }
                })
            },

            // 子传父关闭抽屉
            closeDrawer() {
                this.serListDetailsFlag = false
            },

            // 表格点击事件
            handleClick(row, id) {
                this.id = id
                this.detailsId = row.id
                this.serListDetailsFlag = true
            },

            // 表格鼠标移入事件
            handClick(row) {
            }
        },
        components: {
            dialogMsk,
            tableExample,
            page,
            breadcrumb,
            newDrawer,
            selectTree
        }
    }
</script>

<style scoped lang="less">
    .el-form-item__label {
        font-size: 0.12rem !important;
    }

    .content {
        width: 100%;

        .provider {
            span {
                margin-left: .3rem;
            }
        }
    }

    .details {
        width: 100%;
        position: relative;

        .detailsBox {
            height: 100%;
            margin-top: .2rem;

            .detailsMsg {
                span {
                    color: #999;
                    width: 1.5rem;
                    display: inline-block;
                    text-align: right;
                }

                p {
                    display: inline-block;
                    line-height: .5rem;
                }
            }

            .deployBox {
                width: 100%;

                li {
                    background-color: #eee;
                    display: inline-block;
                    height: 3rem;
                    width: 25%;
                    margin-right: .3rem;
                    margin-bottom: .3rem;
                    margin-left: .5rem;
                    text-align: center;

                    .img {
                        width: 1rem;
                        height: 1rem;
                        margin-left: 37%;
                        margin-top: .5rem;
                    }

                    span {
                        display: inline-block;
                        margin-top: .3rem;
                    }
                }
            }
        }
    }

    .scrollHeight {
        height: 6rem;
        overflow-x: hidden;
        overflow-y: auto;

        .breadcrumb {
            height: 0.15rem;
            margin: 0.2rem 0 0.4rem 0;
            padding-left: 0.1rem;
            border-left: 2px solid #5586FB;
        }

        .inputWidthD {
            width: 3rem;
        }

        .textareaWidthD {
            width: 10.55rem;
            margin: 0.2rem 0 0 -1.9rem;
        }
    }

    .el-dialog__wrapper /deep/ .el-dialog__body {
        padding: 0 0.2rem;
    }
</style>
